from cloudcontrol.exceptions import UnsupportedConnectionError

def create_connection(username, hostname, port = 22, getpass = None, su_source_username = None, su_source_getpass = None):
    """factory method for creating connections,  Returns an object that
    adheres to the AbstractConnection interface"""
    
    import os
    from cloudcontrol._connections.local import LocalUserConnection
    from cloudcontrol._connections.remote import RemoteConnection
    from cloudcontrol._connections.remote import RemoteSuConnection
    
    if hostname == "localhost":
        # we have a local scenario
    
        if username == os.getlogin():
            # local user, on local machine
            return LocalUserConnection()
        
        else:
            # other user, on local machine
            raise UnsupportedConnectionError("currently cannot support local users other than the current user (use os.getlogin() to get the local username)")
    
    else:
        # we have a remote scenario
        if su_source_username:
            # user on remote machine who needs to be SSHed in
            # and then su'd to before it can do anything
            su_from_connection = RemoteConnection(su_source_username, hostname, getpass = su_source_getpass, port = port)
            return RemoteSuConnection(
                su_from_connection = su_from_connection,
                username = username,
                getpass = getpass,
            )
    
        else:
            # this is a user who can remotely log in to the machine
            # and execute commmands
            return RemoteConnection(
                username = username,
                hostname = hostname,
                getpass = getpass,
                port = port,
            )


